﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace FCNS.Net
{
    /// <summary>
    /// 网络应用类
    /// </summary>
   public class Net
    {
        /// <summary>
        /// 下载网络文件
        /// </summary>
        /// <param name="url">网络文件路径</param>
        /// <param name="path">完整的文件保存路径(含文件名与扩展名)</param>
        /// <returns>下载成功则返回 true,否则为 false</returns>
        public bool DownloadFile(string url, string path)
        {
            WebClient DownFile = new WebClient();
            long fbytes;

            //取得文件大小
            WebRequest wr_request = WebRequest.Create(url);
            WebResponse wr_response = wr_request.GetResponse();
            fbytes = wr_response.ContentLength;
            wr_response.Close();
            //开始下载数据
            DownFile.DownloadData(url);
            Stream strm = DownFile.OpenRead(url);
            StreamReader reader = new StreamReader(strm);
            byte[] mbyte = new byte[fbytes];
            int allmybyte = (int)mbyte.Length;
            int startmbyte = 0;
            while (fbytes > 0)
            {
                int m = strm.Read(mbyte, startmbyte, allmybyte);
                if (m == 0) break;
                startmbyte += m;
                allmybyte -= m;
            }
            FileStream fstrm = new FileStream(path, FileMode.Create, FileAccess.Write);
            fstrm.Write(mbyte, 0, startmbyte);
            strm.Close();
            fstrm.Close();
            return true;
        }
    }
}
